<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools :show-before="true">
        <!-- 左侧 -->
        <template v-slot:before>
          <span>共有{{ page.total }}条记录</span>
        </template>
        <!-- 右侧 -->
        <template v-slot:after>
          <el-button
            size="small"
            type="success"
            :disabled="!checkPermission('POINT-USER-ADD')"
            @click="$router.push('/import')"
          >
            excel导入
          </el-button>
          <el-button
            size="small"
            type="danger"
            :disabled="!checkPermission('POINT-USER-ADD')"
            @click="exportData"
          >
            excel导出
          </el-button>
          <el-button
            size="small"
            type="primary"
            :disabled="!checkPermission('POINT-USER-ADD')"
            @click="showDialog = true"
          >
            新增员工
          </el-button>
        </template>
      </PageTools>
      <el-card>
        <!-- 分页组件 -->
        <el-row type="flex" justify="start" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :current-page="page.page"
            :page-size="page.size"
            :total="page.total"
            @current-change="changePage"
          />
        </el-row>
        <el-table v-loading="loading" :data="list" border>
          <el-table-column
            label="序号"
            type="index"
            align="center"
            width="60"
          />
          <el-table-column
            label="姓名"
            prop="username"
            sortable=""
            align="center"
          />
          <el-table-column
            label="照片"
            width="120px"
            prop="username"
            sortable=""
            align="center"
          >
            <template slot-scope="{ row }">
              <img
                v-imagerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                style="border-radius: 50%; width: 75px; height: 75px"
                @click="showQrCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column
            label="手机号"
            prop="mobile"
            sortable=""
            align="center"
          />
          <el-table-column
            label="工号"
            sortable=""
            prop="workNumber"
            align="center"
          />
          <el-table-column
            label="聘用形式"
            sortable=""
            prop="formOfEmployment"
            width="120"
            align="center"
            :formatter="formatEmployment"
          />
          <el-table-column
            label="部门"
            sortable=""
            prop="departmentName"
            align="center"
          />
          <el-table-column
            label="入职时间"
            sortable=""
            prop="timeOfEntry"
            align="center"
          >
            <!-- 作用域插槽 -->
            <template slot-scope="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column
            label="账户状态"
            sortable=""
            prop="enableState"
            width="120"
            align="center"
          >
            <template slot-scope="{ row }">
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            sortable=""
            fixed="right"
            width="280"
            align="center"
          >
            <template slot-scope="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >
                查看
              </el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">
                角色
              </el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
    <Popups :show-dialog.sync="showDialog" />
    <el-dialog title="头像二维码" :visible.sync="showCode">
      <el-row type="flex" justify="center">
        <canvas ref="PhotoCanvas" />
      </el-row>
    </el-dialog>
    <AssignRole
      ref="assignRole"
      :show-role-dialog.sync="showRoleDialog"
      :user-id="userId"
    />
  </div>
</template>

<script>
import { getEmployeesList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/api/constant/employees'
import Popups from './components/addEmployeePopups'
import { formatDate } from '@/filters'
import QrCoed from 'qrcode'
import AssignRole from './components/AssignRole'
export default {
  name: 'Employees',
  components: {
    Popups,
    AssignRole
  },
  props: {},
  data() {
    return {
      list: [],
      page: {
        page: 1,
        size: 10,
        total: 0
      },
      userId: null,
      loading: false,
      showDialog: false,
      showCode: false,
      showRoleDialog: false
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getEmployeesList()
  },
  mounted() { },
  methods: {
    async getEmployeesList() {
      this.loading = true
      const { total, rows } = await getEmployeesList(this.page)
      this.list = rows
      this.page.total = total
      this.loading = false
    },
    changePage(newPage) {
      this.page.page = newPage
      this.getEmployeesList()
    },
    // 格式化数据-聘用形式
    formatEmployment(row, column, cellValue, index) {
      const obj = EmployeeEnum.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    async delEmployee(id) {
      console.log(id)
      try {
        await this.$confirm('确定删除该员工么？')
        await delEmployee(id)
        this.getEmployeesList()
        this.$message.success('操作成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 导出excel
    exportData() {
      const headers = {
        '姓名': 'username',
        '手机号': 'mobile',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '入职日期': 'timeOfEntry',
        '转正日期': 'correctionTime',
        '部门': 'departmentName'
      }
      // 引入导出方法
      import('@/vendor/Export2Excel').then(async excel => {
        // 因为没有接口获取所有的员工数据没次只能获取到10条数据,这里使用获取的条数=总数即可
        const { rows } = await getEmployeesList({ page: 1, size: this.page.total })
        // 获取的数据为key:value 形式数据需要进行转为单一的value形式
        const data = this.formatJson(headers, rows)
        // 复杂表头，处理表的合并
        const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
        const merges = ['A1:A2', 'B1:F1', 'G1:G2']
        excel.export_json_to_excel({
          header: Object.keys(headers), // 表头
          data, // 数据,每条数据对应一条数组。
          filename: '员工信息表', // 导出文件名
          booktype: 'xlsx', // 导出文件类型
          multiHeader,
          merges
        })
      })
    },
    // 数据转换
    formatJson(headers, rows) {
      // return rows.map(item => Object.keys(headers).map(key => item[headers[key]]))
      // 将结果返回
      return rows.map(item => {
        // 外map返回数组嵌套的数据
        return Object.keys(headers).map(key => {
          // 处理数据(格式化入职时间、转正时间；判断入职的数据返回对应值)
          if (headers[key] === 'timeOfEntry' || headers[key] === 'correctionTime') {
            return formatDate(item[headers[key]])
          } else if (headers[key] === 'formOfEmployment') {
            // debugger
            const obj = EmployeeEnum.hireType.find(obj => obj.id === item[headers[key]])
            return obj ? obj.value : '未知'
          }
          // 内map返回单个数据的数组
          return item[headers[key]]
        })
      })
    },
    showQrCode(data) {
      if (data) {
        this.showCode = true
        // 需要页面加载完成否者无法获取到ref
        this.$nextTick(() => {
          QrCoed.toCanvas(this.$refs.PhotoCanvas, data)
        })
      } else {
        this.$message.warning('该用户未上传头像')
      }
    },
    async editRole(id) {
      this.userId = id
      await this.$refs.assignRole.getUserDetailById(id)
      this.showRoleDialog = true
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
